﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using FCMS.Mvc.Security.Principal;

namespace FCMS.Mvc
{
    public class AdminAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (this.isVerfiy)
            {
                UserIdentity identity = WebUtilities.GetIdentity(HttpContext.Current);

                if (identity.IsAnonymous)
                {
                    filterContext.Result = new RedirectResult(GetLoginUrl(filterContext));
                }
            }
        }

        private bool isVerfiy = true;
        public bool IsVerify
        {
            get
            {
                return this.isVerfiy;
            }
            set
            {
                this.isVerfiy = value;
            }
        }

        private string GetLoginUrl(AuthorizationContext filterContext)
        {
            UrlHelper url = new UrlHelper(filterContext.RequestContext);
            var loginUrl = url.Action("login", "main", new { area = "admin" });

            return string.Format(loginUrl + "?returnUrl={0}",
                HttpUtility.UrlEncode(filterContext.HttpContext.Request.RawUrl));
        }
    }
}